//
//  ApiCache.m
//  atlas
//
//  Created by 你好 on 17/2/13.
//  Copyright © 2017年 xyxNav. All rights reserved.
//

#import "ApiCache.h"
#import "NSString+MD5.h"
@implementation ApiCache

+(NSDictionary *)getCacheForUrl:(NSString *)url
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *path = [paths objectAtIndex:0];
    NSLog(@"------------------------------");
    NSLog(@"path=%@",path);
    NSLog(@"++++++++++++++++++++++++++++++");

    
    NSString *filePath=[NSString stringWithFormat:@"%@/%@",path,[url md5]];
    if([[NSFileManager defaultManager]fileExistsAtPath:filePath])
    {
        NSURL *fileUrl=[NSURL fileURLWithPath:filePath];
        NSData *data=[NSData dataWithContentsOfURL:fileUrl options:0 error:nil];
        NSDictionary *attrDic=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        return attrDic;
    }
    return nil;

}

+(BOOL)cacheForUrl:(NSString *)url jsonData:(NSDictionary *)dict
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *path = [paths objectAtIndex:0];
    NSLog(@"------------------------------");
    NSLog(@"path=%@",path);
    NSLog(@"++++++++++++++++++++++++++++++");
    
    NSString *filePath=[NSString stringWithFormat:@"%@/%@",path,[url md5]];
    
    if (![[NSFileManager defaultManager] fileExistsAtPath:filePath])
    {
        NSData *data=[NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
        BOOL isSuccess=[data writeToFile:filePath atomically:YES];
        return isSuccess;
    }
    
    return NO;
}

+(BOOL)isExitCacheForUrl:(NSString *)url
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *path = [paths objectAtIndex:0];
    NSLog(@"------------------------------");
    NSLog(@"path=%@",path);
    NSLog(@"++++++++++++++++++++++++++++++");
    
    NSString *filePath=[NSString stringWithFormat:@"%@/%@",path,[url md5]];
    BOOL isExit=[[NSFileManager defaultManager] fileExistsAtPath:filePath];
    return isExit;
}

@end
